package com.zy.yun.core.interceptor;

import com.zy.yun.base.annotation.NotNullPara;
import com.zy.yun.core.utils.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: wangyanwei
 * @Date: 2018/12/10 16:53
 * @Description: 验证参数非空
 */

@ControllerAdvice
public class NotNullInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        //HandlerMethod 封装方法定义相关的信息,如类,方法,参数等.
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }
        // 获取注解
        NotNullPara notNullPara = ((HandlerMethod) handler).getMethod().getAnnotation(NotNullPara.class);
        if (notNullPara == null) {
            return true;
        }
        // 从参数中得到要判空的字段
        String[] paraKeys = notNullPara.value();
        for (String param : paraKeys) {
            String value = request.getParameter(param);
            if (StringUtils.isBlank(value)) {
                ResponseUtil.paramIsNull(response, param);
                return false;
            }
        }
        return true;
    }


}
